package org.ichamigua.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.ichamigua.user.mapper.UserUpdateAvatarLogMapper;
import org.ichamigua.user.service.UserUpdateAvatarLogService;
import org.ichihamigua.common.framework.entity.Result;
import org.ichihamigua.common.user.dto.UpdateAvatarLogDto;
import org.ichihamigua.common.user.entity.UserEntity;
import org.ichihamigua.common.user.entity.UserUpdateAvatarLogEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;


/**
 * @author zzy
 */
@Service
public class UserUpdateAvatarLogServiceImpl extends ServiceImpl<UserUpdateAvatarLogMapper, UserUpdateAvatarLogEntity> implements UserUpdateAvatarLogService {

    @Resource
    private UserUpdateAvatarLogService userUpdateAvatarLogService;
    @Override
    public long countMonthAvatarUpdate(Long userId) {
        LambdaQueryWrapper<UserUpdateAvatarLogEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserUpdateAvatarLogEntity::getUserId, userId);
        wrapper.eq(UserUpdateAvatarLogEntity::getTime, "YEARMONTH(NOW())");
        return count(wrapper);
    }

    @Override
    public boolean addLog(Long userId, String url) {
        UserUpdateAvatarLogEntity log = new UserUpdateAvatarLogEntity();
        log.setUserId(userId);
        log.setAvatarUrl(url);
        log.setTime(LocalDateTime.now());
        return save(log);
    }

    @Override
    public Result<Page> getAvatar(int page, int pageSize, long id) {
        Page<UserUpdateAvatarLogEntity> avatars = new Page<>(page, pageSize);
        LambdaQueryWrapper<UserUpdateAvatarLogEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserUpdateAvatarLogEntity::getUserId, id);
        userUpdateAvatarLogService.page(avatars, queryWrapper);
        return Result.success(avatars);
    }

    @Override
    public Result<?> deleteBeforeAvatar(Long userId, Long avatarId) {
        LambdaQueryWrapper<UserUpdateAvatarLogEntity> w = new LambdaQueryWrapper<>();
        w.eq(UserUpdateAvatarLogEntity::getUserId, userId);
        w.eq(UserUpdateAvatarLogEntity::getId, avatarId);
        if(!remove(w)) return Result.fail("删除失败");
        //TODO 将七牛云的资源设置为3天后过期
        return Result.success();
    }


}